package cn.jianml.captcha.service.impl;

import cn.jianml.captcha.properties.CaptchaProperties;
import cn.jianml.captcha.service.CaptchaService;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wujian
 * @time 2020/1/7
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private CaptchaProperties properties;

    @Override
    public void create(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String key = request.getParameter("key");
        if(StringUtils.isBlank(key)) throw new Exception("验证码key不能为空");

        setHeader(response, properties.getType());

        Captcha captcha = createCaptcha();

        // TODO: 缓存到redis中

        captcha.out(response.getOutputStream());
    }

    @Override
    public void check(String key, String value) throws Exception {
        // TODO:获取redis中的验证码
        String redisCode = "1234";
        if(StringUtils.isBlank(value)) throw new Exception("请输入验证码");
        if(redisCode == null) throw new Exception("验证码已过期");
        if(!StringUtils.equalsIgnoreCase(value, redisCode)) throw new Exception("验证码不正确");
    }

    private Captcha createCaptcha() {
        Captcha captcha = null;
        if (StringUtils.equalsIgnoreCase(properties.getType(), "gif")) {
            captcha = new GifCaptcha(properties.getWidth(), properties.getHeight(), properties.getLength());
        } else {
            captcha = new SpecCaptcha(properties.getWidth(), properties.getHeight(), properties.getLength());
        }
        captcha.setCharType(properties.getCharType());
        return captcha;
    }

    private void setHeader(HttpServletResponse response, String type){
        if (StringUtils.equalsIgnoreCase(type, "gif")) {
            response.setContentType(MediaType.IMAGE_GIF_VALUE);
        } else {
            response.setContentType(MediaType.IMAGE_PNG_VALUE);
        }
        response.setHeader(HttpHeaders.PRAGMA, "No-cache");
        response.setHeader(HttpHeaders.CACHE_CONTROL, "No-cache");
        response.setDateHeader(HttpHeaders.EXPIRES, 0L);
    }
}
